﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using _404park.Utilities.Extensions;

namespace _404park.ApplicationServices.SearchProvider
{
    public class SearchProviderManager
    {
        private static IDictionary<string, ISearchProvider> _searchProviders = new Dictionary<string, ISearchProvider>();
        private static Random _randomEngine = new Random();

        static SearchProviderManager()
        {
            InitializeSearchProviders();
        }

        public static ISearchProvider PlayDice()
        {
            var selectedSearchProvider = _searchProviders.Values.ToList().PlayDice(x => x.Percentage, _randomEngine);
            return selectedSearchProvider;
        }

        private static void InitializeSearchProviders()
        {
            GetSearchProvider(SearchProvider.Google.ToString());
            GetSearchProvider(SearchProvider.Yahoo.ToString());
            GetSearchProvider(SearchProvider.SelfGoogle.ToString());
        }

        public static ISearchProvider GetSearchProvider(string name)
        {
            if (_searchProviders.ContainsKey(name))
                return _searchProviders[name];

            var searchProvider = Factory(name);
            _searchProviders.Add(name, searchProvider);

            return searchProvider;
        }

        private static ISearchProvider Factory(string name)
        { 
            ISearchProvider searchProvider = null;

            if (name.Equals(SearchProvider.Google.ToString(), StringComparison.InvariantCultureIgnoreCase))
                searchProvider = new GoogleSearchProvider(30);
            else if (name.Equals(SearchProvider.Yahoo.ToString(), StringComparison.InvariantCultureIgnoreCase))
                searchProvider = new YahooSearchProvider(40);
            else if (name.Equals(SearchProvider.SelfGoogle.ToString(), StringComparison.InvariantCultureIgnoreCase))
                searchProvider = new SelfHostedGoogleSearchProvider(30);

            return searchProvider;
        }

        public enum SearchProvider
        {
            Google = 1,
            Yahoo,
            SelfGoogle
        }
    }
}
